<template>
  <div class="my-products">
    <el-container>
      <el-header>
        <div class="header-content">
          <div class="header-left">
            <el-button type="primary" @click="router.push('/')">
              <el-icon><ArrowLeft /></el-icon>
              返回主页
            </el-button>
          </div>
          <div class="header-center">
            <img src="https://susu-plants.oss-cn-beijing.aliyuncs.com/2025-03-04-22-13-33QQ20250304-190757.png" alt="Logo" class="logo-image">
            <h2>我的农产品</h2>
          </div>
        </div>
      </el-header>
      <el-main>
        <div class="content">
          <el-card class="table-card">
            <template #header>
              <div class="card-header">
                <h3>我的农产品列表</h3>
              </div>
            </template>
            
            <!-- 商品表格 -->
            <el-table 
              :data="products" 
              style="width: 100%"
              v-loading="loading"
            >
              <el-table-column label="农场名称" prop="farmName" min-width="120" />
              
              <el-table-column label="商品图片" width="120">
                <template #default="scope">
                  <el-image
                    :src="getPrimaryImage(scope.row.images)"
                    fit="cover"
                    style="width: 80px; height: 80px"
                    :preview-src-list="getImageUrls(scope.row.images)"
                  />
                </template>
              </el-table-column>
              
              <el-table-column prop="productName" label="商品名称" min-width="120" />
              
              <el-table-column label="分类" min-width="120">
                <template #default="scope">
                  <el-tag
                    v-for="category in scope.row.categories"
                    :key="category.category_id"
                    class="mx-1"
                    size="small"
                  >
                    {{ category.category_name }}
                  </el-tag>
                </template>
              </el-table-column>
              
              <el-table-column prop="productDescription" label="商品描述" min-width="200">
                <template #default="scope">
                  <el-tooltip
                    :content="scope.row.productDescription"
                    placement="top"
                    :show-after="500"
                  >
                    <span class="description-text">{{ scope.row.productDescription }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>
              
              <el-table-column prop="price" label="价格" width="120">
                <template #default="scope">
                  <span class="price">¥{{ scope.row.price }}</span>
                </template>
              </el-table-column>
              
              <el-table-column prop="stock" label="库存" width="100">
                <template #default="scope">
                  <span>{{ scope.row.stock }}</span>
                </template>
              </el-table-column>
              
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
                    {{ scope.row.status === 1 ? '上架中' : '已下架' }}
                  </el-tag>
                </template>
              </el-table-column>
              
              <el-table-column label="操作" width="100" fixed="right">
                <template #default="scope">
                  <el-button-group>
                    <el-button
                      type="primary"
                      size="small"
                      @click="handleViewProduct(scope.row)"
                    >
                      查看
                    </el-button>
                  </el-button-group>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { getUserProducts } from '@/api/products'

const router = useRouter()
const loading = ref(true)
const products = ref([])

// 获取用户的所有商品
const loadProducts = async () => {
  try {
    loading.value = true
    const res = await getUserProducts()
    
    if (Array.isArray(res)) {
      products.value = res.map(item => ({
        ...item.product,
        farmName: item.farmName,
        images: item.images || [],
        categories: item.categories || [],
        status: item.product.status  // 确保状态字段被正确映射
      }))
    } else {
      console.warn('商品列表数据格式不正确:', res)
      products.value = []
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error(error.message || '加载数据失败，请重试')
    products.value = []
  } finally {
    loading.value = false
  }
}

// 查看商品详情
const handleViewProduct = (product) => {
  router.push(`/product/${product.farmId}/${product.productId}`)
}

// 获取主图
const getPrimaryImage = (images) => {
  if (!images || images.length === 0) {
    return 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
  }
  const primaryImage = images.find(img => img.isPrimary === 1)
  return primaryImage ? primaryImage.imageUrl : images[0].imageUrl
}

// 获取所有图片URL列表（用于预览）
const getImageUrls = (images) => {
  if (!images || images.length === 0) {
    return []
  }
  return images.map(img => img.imageUrl)
}

onMounted(() => {
  loadProducts()
})
</script>

<style scoped>
.my-products {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.el-header {
  padding: 0;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.header-left {
  flex: 0 0 auto;
}

.header-center {
  flex: 1;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.logo-image {
  height: 40px;
  width: auto;
}

.header-center h2 {
  margin: 0;
  color: #409EFF;
}

.el-main {
  padding: 20px;
  margin: 80px auto 0;
  max-width: 1400px;
}

.content {
  margin-top: 20px;
}

.table-card {
  background-color: #fff;
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.description-text {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.el-table {
  margin-top: 20px;
}

.el-button-group {
  display: flex;
  gap: 5px;
}

.mx-1 {
  margin: 0 4px;
}

.el-tag + .el-tag {
  margin-left: 4px;
}
</style> 